package com.naicheng.ivote.views;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler.Callback;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.naicheng.ivote.R;
import com.naicheng.ivote.adapter.HotMainListAdapter;
import com.naicheng.ivote.adapter.TitleSelectAdapter;
import com.naicheng.ivote.constant.ConstantMine;
import com.naicheng.ivote.doman.BaseResponseEntity;
import com.naicheng.ivote.doman.HotMainlistItemBean;
import com.naicheng.ivote.doman.HotMainlistItemDetailBean;
import com.naicheng.ivote.doman.TitleSelectlistBean;
import com.naicheng.ivote.engin.BaseActivity;
import com.naicheng.ivote.parser.BaseParser;
import com.naicheng.ivote.uiself.ToastUtils;
import com.naicheng.ivote.uiself.XListView;
import com.naicheng.ivote.uiself.XListView.IXListViewListener;
import com.naicheng.ivote.utils.AppManager;
import com.naicheng.ivote.utils.MyPreferences;
import com.naicheng.ivote.volley.Response.Listener;

public class TypeMainActivity extends BaseActivity implements Callback,IXListViewListener{
	
	
	TypeMainActivity CTHMA=TypeMainActivity.this;
	private MyPreferences preference;
	AppManager appManager = AppManager.getAppManager();
	private LayoutInflater inflater;
	
	private Handler handler;
	// PopupWindow对象
	private PopupWindow selectPopupWindow = null;
	// 自定义Adapter
	private TitleSelectAdapter titleAdapter = null;
	private ArrayList<TitleSelectlistBean> titleList;
	// 展示所有下拉选项的ListView
	private ListView listView = null;
	
	private HotMainListAdapter listAdapter;
	
	private boolean isXlist=false;//是否是下拉后者上拉刷新
	private boolean isXlistDown=false;//是否是下拉刷新
	private TitleSelectlistBean TitleBean;
	private HotMainlistItemBean HotListBean;
	private ArrayList<HotMainlistItemDetailBean> hotMainList;
	
	private String content="";//评论内容
	
	private HashMap<String, String> map;
	
	
	
	private TextView hot_main_title1;
	private LinearLayout hot_main_title_ll;
	private XListView hot_main_list;
	
	
	@Override
	protected void setConentView() {
		super.setConentView();
		setContentView(R.layout.activity_hot_main);
	}
	@Override
	protected void init() {
		super.init();
		preference=MyPreferences.getPrefer(CTHMA, "myconfig");
		inflater=getLayoutInflater();
		
		titleList=new ArrayList<TitleSelectlistBean>();
		hotMainList=new ArrayList<HotMainlistItemDetailBean>();
		HotListBean=new HotMainlistItemBean();
		handler=new Handler(CTHMA);
		
		hot_main_title1=(TextView) findViewById(R.id.hot_main_title1);
		hot_main_title_ll=(LinearLayout) findViewById(R.id.hot_main_title_ll);
		hot_main_list=(XListView) findViewById(R.id.hot_main_list);
		
		hot_main_list.setPullLoadEnable(true);
		hot_main_list.setXListViewListener(CTHMA);
		
		
		
	}
	@Override
	protected void processLogic() {
		super.processLogic();
		
		//检查网络是否连接
		if(ConstantMine.isNetConn){
//			getNetDataDefaulthottype();
			getNetDataHottypelist();
		}else{
			ToastUtils.getCenterDownToast(CTHMA, "未发现网络连接，请检查网络！");
		}
		
		//点击item，进入详情页
		hot_main_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				
			}
		});
		
	}
	@Override
	protected void setOnClickListener() {
		hot_main_title1.setOnClickListener(CTHMA);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.hot_main_title1:
			
			if(null==titleList){
				ToastUtils.getCenterDownToast(CTHMA, "暂无数据！");
			}else{
				System.out.println("getWidth:"+hot_main_title_ll.getWidth());
				initPopuWindow(hot_main_title_ll.getWidth());
				popupWindwShowing(hot_main_title_ll);
			}
			
			break;

		
		}
	}
	
	
	/**
	 * 获取热榜默认标题
	 */
	
	public void getNetDataDefaulthottype(){
		
		map=new HashMap<String, String>();
		super.getDataFromServer("defaulthottype", map, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				BaseResponseEntity<TitleSelectlistBean> mResponse = new BaseParser<TitleSelectlistBean>().parserDomain(response, TitleSelectlistBean.class);
				if (mResponse != null && mResponse.getState()) {
					TitleBean=mResponse.getSingleDomain();
					hot_main_title1.setText(TitleBean.getName());
					if(null!=TitleBean){
						getNetDataHotlist(TitleBean.getId());
					}
				}else{
					ToastUtils.getCenterDownToast(CTHMA, mResponse.getMsg());
				}
			}
			
		}, CTHMA);
		
		
	}
	/**
	 * 获取热榜标题列表
	 */
	
	public void getNetDataHottypelist(){
		
		map=new HashMap<String, String>();
		super.getDataFromServer("type", map, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				BaseResponseEntity<TitleSelectlistBean> mResponse = new BaseParser<TitleSelectlistBean>().parserCollection(response, TitleSelectlistBean.class);
				if (mResponse != null && mResponse.getState()) {
					titleList=(ArrayList<TitleSelectlistBean>) mResponse.getData();
					System.out.println(titleList.size());
					hot_main_title1.setClickable(true);
					for (int i = 0; i < titleList.size(); i++) {
						if(titleList.get(i).isDefault()){
							hot_main_title1.setText(titleList.get(i).getName());
							getNetDataHotlist(titleList.get(i).getId());
						}
					}
				}else{
					ToastUtils.getCenterDownToast(CTHMA, mResponse.getMsg());
				}
			}
			
		}, CTHMA);
		
	}
	
	/**
	 * 获取热榜数据列表
	 */
	
	public void getNetDataHotlist(int id){
		
		map=new HashMap<String, String>();
		map.put("userid", "1");
//		map.put("userid", MyApplication.user.userid);
		map.put("id", id+"");
		map.put("page", "1");
		map.put("size", "30");
		super.getDataFromServer("votelist", map, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				System.out.println(response.toString());
				BaseResponseEntity<HotMainlistItemBean> mResponse = new BaseParser<HotMainlistItemBean>().parserDomain(response, HotMainlistItemBean.class);
				if (mResponse != null && mResponse.getState()) {
					
					HotListBean=mResponse.getSingleDomain();
					if(null==HotListBean){
						ToastUtils.getCenterDownToast(CTHMA, "暂无列表数据！");
					}else{
						if(isXlistDown){
							hotMainList.addAll(HotListBean.getQuestions());
						}else{
							hotMainList=HotListBean.getQuestions();
						}
						System.out.println(hotMainList.size());
						listAdapter=new HotMainListAdapter(hotMainList, CTHMA, handler, "hot");
						hot_main_list.setAdapter(listAdapter);
						if(isXlist){
							onLoad();
						}
					}
					
					
				}else{
					ToastUtils.getCenterDownToast(CTHMA, mResponse.getMsg());
				}
			}
			
		}, CTHMA);
		
	}
	/**
	 * 获取热榜详情
	 */
	
	public void getNetDataQuestionnaire(){
		
	}
	
	
	
	
	
	/**
	 * 初始化PopupWindow
	 */
	private void initPopuWindow(int mywidth) {
		// PopupWindow浮动下拉框布局
		View mywindow = CTHMA.getLayoutInflater().inflate(R.layout.activity_listselect_main, null);
		listView = (ListView) mywindow.findViewById(R.id.listselect_main_list);
		// 设置自定义Adapter
		titleAdapter = new TitleSelectAdapter(CTHMA, handler, titleList);
		listView.setAdapter(titleAdapter);
		selectPopupWindow = new PopupWindow(mywindow, mywidth, android.view.ViewGroup.LayoutParams.WRAP_CONTENT,true);
		selectPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		selectPopupWindow.setOutsideTouchable(true);
	}

	/**
	 * 显示PopupWindow窗口
	 * 
	 * @param popupwindow
	 */
	private void popupWindwShowing(View parent) {
		// 防止下拉框与文本框之间产生缝隙，影响界面美化
		selectPopupWindow.showAsDropDown(parent, 0, -3);
	}

	/**
	 * PopupWindow消失
	 */
	private void dismiss() {
		selectPopupWindow.dismiss();
	}

	
	@Override
	public boolean handleMessage(Message msg) {
		Bundle data = msg.getData();
		int id;
		switch (msg.what) {
		case 0:
			int selIndex = data.getInt("selIndex");
			hot_main_title1.setText(titleList.get(selIndex).getName());
			getNetDataHotlist(titleList.get(selIndex).getId());
			TitleBean=titleList.get(selIndex);
//			System.out.println("getId():"+titleList.get(selIndex).getId());
//			System.out.println("userId():"+MyApplication.user.userid);
			dismiss();
			break;

		case 1:
			//取消赞
			id= data.getInt("id");
			System.out.println("id:"+id);
			itemNetBut("cancelpraise",id,null);
			
			break;
		case 2:
			//赞
			id = data.getInt("id");
			System.out.println("id1:"+id);
			itemNetBut("praise",id,null);
			break;
		case 3:
			//评论
			id = data.getInt("id");
			commentDialog(id);
			break;
		case 4:
			//取消举报
			id = data.getInt("id");
			itemNetBut("cancelreport",id,null);
			break;
		case 5:
			//举报
			id = data.getInt("id");
			itemNetBut("report",id,null);
			break;
		case 6:
			break;
		
		}
		
		return false;
	}
	
	
	
	@Override
	public void onRefresh() {
		System.out.println("刷拉");
		ConstantMine.ISreflesh=true;
		isXlist=true;
		if(null!=TitleBean){
			getNetDataHotlist(TitleBean.getId());
		}
		
	}
	@Override
	public void onLoadMore() {
		System.out.println("刷完拉");
		isXlist=true;
		isXlistDown=true;
		if(null!=TitleBean){
			getNetDataHotlist(TitleBean.getId());
		}
		
	}
	
	private void onLoad() {
		ConstantMine.ISreflesh=false;
		hot_main_list.stopLoadMore();
		hot_main_list.stopRefresh();
		isXlist=false;
		isXlistDown=false;
	}
	
	
	/**
	 * 列表item按钮点击接口，赞,评论，举报
	 */
	public void itemNetBut(final String method,int id,String content){
		
		map=new HashMap<String, String>();
		map.put("userid", "1");
//		map.put("userid", MyApplication.user.userid);
		map.put("id", id+"");
		if("comment".equals(method)){
			map.put("content", content);
		}
		
		super.getDataFromServer(method, map, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				System.out.println("response--------->"+response.toString());
				BaseResponseEntity<String> mResponse = new BaseParser<String>().parserString(response);
				if (mResponse != null && mResponse.getState()) {
					if("comment".equals(method)){
						ToastUtils.getCenterDownToast(CTHMA, "评论成功！");
//						hot_main_list.setAdapter(listAdapter);
					}	
					listAdapter.notifyDataSetChanged();
				}else{
					ToastUtils.getCenterDownToast(CTHMA, mResponse.getMsg());
				}
			}
			
		}, CTHMA);
		
	}
	
	/**
	 * 列表item按钮点击，评论对话框
	 */
	public void commentDialog(final int id){
		
		View view=inflater.inflate(R.layout.comment_dialog, null);
		final Dialog dialog=new Dialog(CTHMA, R.style.dialog);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		dialog.addContentView(view, params);
		final EditText comment_dialog_content=(EditText) view.findViewById(R.id.comment_dialog_content);
		final TextView comment_dialog_num=(TextView) view.findViewById(R.id.comment_dialog_num);
		Button comment_dialog_but=(Button) view.findViewById(R.id.comment_dialog_but);
		comment_dialog_num.setText(""+99);
		
		comment_dialog_content.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				content=comment_dialog_content.getText().toString();
				if(99<=content.length()){
					s=s.subSequence(0, 99);
					content=content.subSequence(0, 99).toString();
				}
				
				comment_dialog_num.setText(""+(99-content.length()));
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
				content=comment_dialog_content.getText().toString();
				if(99<=content.length()){
					content=content.subSequence(0, 99).toString();
				}
				comment_dialog_num.setText(""+(99-content.length()));
			}
		});
		
		comment_dialog_but.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				itemNetBut("comment",id,content);
				InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
				imm.hideSoftInputFromWindow(comment_dialog_content.getWindowToken(), 0); 
				dialog.dismiss();
			}
		});
		
		Window window = dialog.getWindow();
		window.setGravity(Gravity.BOTTOM);
		WindowManager.LayoutParams lp = window.getAttributes();
		window.setAttributes(lp);
		dialog.show();
	}
	

}
